<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/
jimport( 'joomla.application.component.view' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardViewJAJobAlerts extends JView
{
    /**
     * Display the view
     */
    function display($tmpl = null){
    
       switch ($this->getLayout())
  		{  	  					
  			case 'element_user':
				$this->element_user();
				break;
  			case 'form':	
  				$this->edit();  				  				
  				break;
  			default:
  				$this->setLayout('default');
  				$this->displayList();
  		}
  		
        parent::display($tmpl);
  	}
  	
  	function displayList()
  	{
  		global $mainframe, $option;
        $option_1 = $option.'.jajobalerts';
		$lists['order']		= $mainframe->getUserStateFromRequest( $option_1.'.filter_order',		'filter_order',		'posted_date',	'cmd' );
		$lists['order_Dir']	= $mainframe->getUserStateFromRequest( $option_1.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$lists['option']	= $option;
		
        // get data items
        $items = &$this->get('Items');        

//        $pagination = &$this->get('Pagination');
        
        $this->assignRef('lists', $lists);
        $this->assignRef('items', $items);
//        $this->assignRef('pagination', $pagination);
  	}
  
  	/**
  	* Display edit form
  	*/
  	function edit($postback=false)
  	{  		  		
  		$item = $this->get('Item');
  		if ($item->id==null)
  			$item->posted_date = date("Y-m-d");
    	// Make sure you are logged in and have the necessary access rights
        if($postback){
            $post    = JRequest::get('request', JREQUEST_ALLOWHTML);
            $item->bind($post);
        }
        
        $item->category = explode(',',$item->category);
        $item->location = explode(',',$item->location);
        $objCategory = $this->getCategoryCombo_for_jobalert($item->category);
        $objLocation = $this->getLocationCombo_for_jobalert($item->location);
        $this->assignRef('item', $item);
        $objSendMailDuration = $this->getSendMailDurationCombo($item->sendmail_duration);
        $objPostedDate = $this->getPostedDate($item->posted_date);
        $objJobType = $this->getJobType_for_jobalert($item->job_type);
//        $objJobDistance = $this->getJobDistance(explode(',',$item->job_distance));
        $this->assignRef('objCategory',$objCategory);
        $this->assignRef('objLocation',$objLocation);
        $this->assignRef('objSendMailDuration',$objSendMailDuration);
        $this->assignRef('objPostedDate',$objPostedDate);
        $this->assignRef('objJobType',$objJobType);
//        $this->assignRef('objJobDistance',$objJobDistance);
        $temp = JRequest::getInt('Itemid', 0);
        $this->assignRef('Itemid', $temp);
    }
    
    function view(){
		$user = JFactory::getUser(); 
    	
    	$item = $this->get('ItemView');
    	if (isset($item))
	    	if ($item->user_id!=$user->id)
	    		checkPermission('view_resume_details');
        $Itemid = JRequest::getVar('Itemid');
        
        // Check if user has a resume
        if (isset($item))
	        if(!$item->id){          
	            return;
	        }
        
        $mail_postback = JRequest::getVar('mail_postback',false);
        $mail_postback_jobseeker = JRequest::getVar('mail_postback_jobseeker',false);
    	if ($mail_postback || $mail_postback_jobseeker)
    	{
    		$mail_data = array();
	    	$mail_data['youremail'] = JRequest::getVar('youremail');
	    	$mail_data['friendemail'] = JRequest::getVar('friendemail');
	    	$mail_data['subject'] = JRequest::getVar('subject');
	    	$mail_data['message'] = JRequest::getVar('message');
    	}                      
    	$this->assignRef('mail', $mail_data);
        
        $fieldList = $this->get('EditFieldList');
        $fromsearch = JRequest::getVar('fromsearch');
        
        $this->assignRef('item', $item);
        $this->assignRef('fieldlist', $fieldList);
        $this->assignRef('Itemid', $Itemid);
        $this->assignRef('fromsearch', $fromsearch);
        
    }
    
    
	function &_getViewLists($fieldList){
		global $mainframe, $option;

		$db = &JFactory::getDBO();
		
        
		$lists['order']		= $mainframe->getUserStateFromRequest( $option.".jaresumes.filter_order",		'filter_order',		'a.created_date',	'cmd' );
		$lists['order_Dir']	= $mainframe->getUserStateFromRequest( $option.".jaresumes.filter_order_Dir",	'filter_order_Dir',	'ASC',			'word' );
		$search				= JRequest::getVar('resume_search');//$mainframe->getUserStateFromRequest( $option.".jaresumes.search",			'search',			'',				'string' );
		$search				= JString::strtolower( $search );        
				
		/* search filter */
		$lists['search']= $search;
		$item = new stdClass();
		
		foreach ($fieldList as $field){
			if($field->is_on_filter){
				$item->{$field->field_name} = $mainframe->getUserStateFromRequest( $option.".jaresumes.".$field->field_name,   $field->field_name,   '', 'string' );
				$lists['filter'][$field->field_name] = rendfield($item, $field, true);
			}
		}

        // filter_state
        $lists['option']    = $option;
		
		return $lists;
	}

	function treerecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 )
	{
		if (@$children[$id] && $level <= $maxlevel)
		{
			if (is_array($children))
			foreach ($children[$id] as $v)
			{
				$id = $v->id;

				if ( $type ) {
					$pre 	= '<sup>|_</sup>&nbsp;';
					$spacer = '.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
				} else {
					$pre 	= '- ';
					$spacer = '&nbsp;&nbsp;';
				}

				if ( $v->parent_id == 0 ) {
					$txt 	= $v->name;
				} else {
					$txt 	= $pre . $v->name;
				}
				$pt = $v->parent_id;
				$list[$id] = $v;
				$list[$id]->treename = "$indent$txt";
				$list[$id]->pretext = $pre;
				$list[$id]->children = count( @$children[$id] );
				$list = treeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
			}
		}
		
		
		return $list;
	}	
	

	function getMultiLevelOptions($table_name)
	{
		$db = JFactory::getDBO();
    	$query = "SELECT * FROM #__$table_name  WHERE published=1";         
        $db->setQuery($query);
        $objects = $db->loadObjectList();
        $objectHTML = array();
        
        $objectHTML[] = JHTML::_('select.option',  "", JText::_("Please select")."...");
        
    	$children = array();	
    	if ($objects)
        {
        	foreach ($objects as $v )
			{
				$pt = $v->parent_id;			
				$list = @$children[$pt] ? $children[$pt] : array();
				array_push( $list, $v );
				$children[$pt] = $list;
			}
			if (is_array($children))
			{
				
				foreach ($children as $key=>$value)
				{
					$temp = array();
					$tmp_children = array();
					if (is_array($children[$key]))
					{
						foreach ($children[$key] as $k=>$v)
							$temp[$k] = $v->name;
						asort($temp);	
						foreach ($temp as $k=>$v)
							$tmp_children[$k] = $children[$key][$k];
						$children[$key] = $tmp_children;
					}
				}
				
			}
			$list = treerecurse(0, '', array(), $children );
			if($list){
				foreach ($list as $i => $item) {
					$treename = $item->treename;			
					$treename = JFilterOutput::ampReplace($treename);
					$treename = str_replace('"', '&quot;', $treename);
					if($item->id == 0)
						$list[$i]->treename = $treename;
					else 	
						$list[$i]->treename = $treename;
				}
			}
			$objects = $list;
        }
        
        return $objects;		
	}
	
	function getCategoryCombo($selected_value)
	{
		$r = '<input type="text" value="'.JText::_("Search category").'" onblue="if(this.value == \'\') this.value=\''.JText::_("Search category").'\';" onfocus="if(this.value == \''.JText::_("Search category").'\') this.value=\'\';" id="auto_category" style="width:250px; color:#A9A9A9"/><div class="job_search_category">';
		$categoryOptions = $this->getMultiLevelOptions('ja_categories');
		$this->initialCat_JSVar($categoryOptions);
		foreach ($categoryOptions as $key=>$value)
		{
			if (!in_array($value->id,$selected_value))
				$r .= '<input onclick="checkbox_clicked(this, \'category\', 0)" id="category_'.$value->id.'" type="checkbox" name="cat_id[]" alt="'.$key.'" value="'.$value->name.'" /><label for="category_'.$value->id.'">'.$value->treename.'</label><br />';
			else 	
				$r .= '<input onclick="checkbox_clicked(this, \'category\', 0)" checked id="category_'.$value->id.'" type="checkbox" name="cat_id[]" alt="'.$key.'" value="'.$value->name.'" /><label for="category_'.$value->id.'">'.$value->treename.'</label><br />';
		}
		$r .= "</div>";
		return $r;
	}
	
	function getLocationCombo($selected_value)
	{
		$r = '<input type="text" value="'.JText::_("Search location").'" onblue="if(this.value == \'\') this.value=\''.JText::_("Search location").'\';" onfocus="if(this.value == \''.JText::_("Search location").'\') this.value=\'\';" id="auto_location" style="width:250px; color:#A9A9A9"/><div class="job_search_category">';
		$locationOptions = $this->getMultiLevelOptions('ja_location');
		$this->initialLocation_JSVar($locationOptions);
		foreach ($locationOptions as $key=>$value)
		{
			if (!in_array($value->id,$selected_value))
				$r .= '<input onclick="checkbox_clicked(this, \'location\', 0)" id="location_'.$value->id.'" type="checkbox" name="location_id[]" alt="'.$key.'" value="'.$value->name.'" /><label for="location_'.$value->id.'">'.$value->treename.'</label><br />';
			else 
				$r .= '<input onclick="checkbox_clicked(this, \'location\', 0)" id="location_'.$value->id.'" type="checkbox" name="location_id[]" alt="'.$key.'" value="'.$value->name.'" /><label for="location_'.$value->id.'">'.$value->treename.'</label><br />';
		}
		$r .= "</div>";
		return $r;
	}
	

	function getCategoryCombo_for_jobalert($selected_value)
	{
		$r = '<input type="text" value="'.JText::_("Search category").'" onblue="if(this.value == \'\') this.value=\''.JText::_("Search category").'\';" onfocus="if(this.value == \''.JText::_("Search category").'\') this.value=\'\';" id="auto_category" style="width:250px; color:#A9A9A9"/><div class="clsCategory">';
		$categoryOptions = $this->getMultiLevelOptions('ja_categories');
		$this->initialCat_JSVar($categoryOptions);
		foreach ($categoryOptions as $key=>$value)
		{
			if (!in_array($value->id,$selected_value))
				$r .= '<input onclick="checkbox_clicked(this, \'category\', 0)" id="category_'.$value->id.'" type="checkbox" name="category[]" value="'.$key.'" /><label for="category_'.$value->id.'">'.$value->treename.'</label><br />';
			else 	
				$r .= '<input onclick="checkbox_clicked(this, \'category\', 0)" checked id="category_'.$value->id.'" type="checkbox" name="category[]" value="'.$key.'" /><label for="category_'.$value->id.'">'.$value->treename.'</label><br />';
		}
		$r .= "</div>";
		return $r;
	}
	
	function getLocationCombo_for_jobalert($selected_value)
	{
		$r = '<input type="text" value="'.JText::_("Search location").'" onblue="if(this.value == \'\') this.value=\''.JText::_("Search location").'\';" onfocus="if(this.value == \''.JText::_("Search location").'\') this.value=\'\';" id="auto_location" style="width:250px; color:#A9A9A9"/><div class="clsLocation">';
		$locationOptions = $this->getMultiLevelOptions('ja_location');
		$this->initialLocation_JSVar($locationOptions);
		foreach ($locationOptions as $key=>$value)
		{
			if (!in_array($value->id,$selected_value))
				$r .= '<input onclick="checkbox_clicked(this, \'location\', 0)" id="location_'.$value->id.'" type="checkbox" name="location[]" value="'.$key.'" /><label for="location_'.$value->id.'">'.$value->treename.'</label><br />';
			else 
				$r .= '<input onclick="checkbox_clicked(this, \'location\', 0)" checked id="location_'.$value->id.'" type="checkbox" name="location[]" value="'.$key.'" /><label for="location_'.$value->id.'">'.$value->treename.'</label><br />';
		}
		$r .= "</div>";
		return $r;
	}
	
	function getJobType_for_jobalert($selected_value)
	{
		$htmlOptions = array();
		$htmlOptions[] = JHTML::_('select.option', '',JText::_('All'));
		$db = JFactory::getDBO();
		$query = "SELECT value,text FROM #__ja_codes WHERE field_id='ja_jobs_job_type'";
		$db->setQuery($query);
		$result = $db->loadObjectList();
		if (is_array($result))
			for ($i=0;$i<count($result);$i++)
				$htmlOptions[] = JHTML::_('select.option', $result[$i]->value,JText::_($result[$i]->text));
		$htmlJobType = JHTML::_('select.genericlist',$htmlOptions,'job_type','style="width:150px;"','value','text',$selected_value);
		return $htmlJobType;
	}
	
	function getSendMailDurationCombo($selected_value='')
	{
		$htmlOptions = array();
		$htmlOptions[] = JHTML::_('select.option', '0',JText::_('None'));
		$htmlOptions[] = JHTML::_('select.option', '1',JText::_('Daily'));
		$htmlOptions[] = JHTML::_('select.option', '7',JText::_('Weekly'));
		$htmlOptions[] = JHTML::_('select.option', '14',JText::_('Bi-Weekly'));
		$htmlOptions[] = JHTML::_('select.option', '30',JText::_('Monthly'));
		$htmlDuration = JHTML::_('select.genericlist',$htmlOptions,'sendmail_duration','style="width:150px;"','value','text',$selected_value);
		return $htmlDuration;
	}
	
	function getPostedDate($selected_value='')
	{
		$htmlOptions = array();
		$htmlOptions[] = JHTML::_('select.option', '',JText::_('All'));
		$htmlOptions[] = JHTML::_('select.option', '1','1 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '2','2 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '3','3 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '4','4 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '5','5 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '6','6 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '7','7 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '8','8 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '9','9 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '10','10 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '11','11 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '12','12 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '13','13 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '14','14 '.JText::_('day(s)'));
		$htmlOptions[] = JHTML::_('select.option', '30','30 '.JText::_('day(s)'));
		$htmlPostedDate = JHTML::_('select.genericlist',$htmlOptions,'posted_date','style="width:150px;"','value','text',$selected_value);
		return $htmlPostedDate;
	}
	
	function getJobDistance($selected_value)
	{
		$htmlOptions = array();
		$htmlOptions[] = JHTML::_('select.option', '',JText::_('All'));
		$db = JFactory::getDBO();
		$query = "SELECT value,text FROM #__ja_codes WHERE field_id='ja_jobs_distance' ORDER BY value";
		$db->setQuery($query);
		$result = $db->loadObjectList();
		if (is_array($result))
			for ($i=0;$i<count($result);$i++)
				$htmlOptions[] = JHTML::_('select.option', $result[$i]->value,JText::_($result[$i]->text));
		$htmlJobType = JHTML::_('select.genericlist',$htmlOptions,'job_distance[]',' multiple style="width:150px;"','value','text',$selected_value);
		return $htmlJobType;
	}
	
	function getJobType($selected_value)
	{
		$htmlOptions = array();
		$htmlOptions[] = JHTML::_('select.option', '',JText::_('All'));
		$db = JFactory::getDBO();
		$query = "SELECT text as value,text FROM #__ja_codes WHERE field_id='ja_jobs_job_type'";
		$db->setQuery($query);
		$result = $db->loadObjectList();
		if (is_array($result))
			for ($i=0;$i<count($result);$i++)
				$htmlOptions[] = JHTML::_('select.option', $result[$i]->value,JText::_($result[$i]->text));
		$htmlJobType = JHTML::_('select.genericlist',$htmlOptions,'job_type','style="width:150px;"','value','text',$selected_value);
		return $htmlJobType;
	}
	
	function element_user()
	{
		global $mainframe;
		
		$element_user = $this->get('UserList');
		$this->setLayout('element_user');
		$this->assignRef('items',$element_user);
		
		$search	= $mainframe->getUserStateFromRequest( JBCOMNAME .".jaemployers.search",			'user_search',			'',				'string' );
		$search = trim($search);
		
		$this->assignRef('search', $search);
		$pagination = $this->get('EmPagination');
		$this->assignRef('pagination',$pagination);
		
	}
	
	function initialCat_JSVar($arr_category)
	{
		echo '<script type="text/javascript" src="'.JURI::root().'components/com_jajobboard/js/jquery.js" language="javascript"></script>';
		echo '<script type="text/javascript" src="'.JURI::root().'components/com_jajobboard/js/jquery.autocomplete.js" language="javascript"></script>';
		echo '<link rel="stylesheet" type="text/css" href="'.JURI::root().'components/com_jajobboard/js/jquery.autocomplete.css" />';
		echo '<script type="text/javascript" language="javascript">';
		echo '/* <![CDATA[ */';
		echo 'child_category = new Array();';
		foreach ($arr_category as $key=>$value)
		{
			echo 'child_category['.$value->id.']=new Array();';
		}
		foreach ($arr_category as $key=>$value)
			if ($value->parent_id!=0)
			{
				echo 'temp_len = child_category['.$value->parent_id.'].length;';
				echo 'child_category['.$value->parent_id.'][temp_len]='.$value->id.';';
			}
				
		echo "var data_category = [";
		$i=0;
		foreach ($arr_category as $key=>$value){
			if($i < count($arr_category)-1)
				echo "{id: 'category_".$value->id."', value: '".$value->name."'},";
			else echo "{id: 'category_".$value->id."', value: '".$value->name."'}";
			$i++;
		}
		echo "];
		
		jQuery().ready(function() {			
			jQuery('#auto_category').autocomplete(data_category, {
				minChars: 0,
				width: 250,
				matchContains: 'word',
				autoFill: false,
				formatItem: function(row, i, max) {
					return  row.value;
				},
				formatMatch: function(row, i, max) {
					return row.id + ' ' + row.value;
				},
				formatResult: function(row) {
					return row.value;
				}

			}).result(function(event, data, formatted) {
				jQuery('#'+data.id).attr('checked', 'checked');
				checkbox_clicked(document.getElementById(data.id), 'category', 0);
				jQuery('#'+data.id).focus();
			});
		});";
		
		echo '/* ]]> */';
		echo '</script>';		
	}
	
	function initialLocation_JSVar($arr_location)
	{
		echo '<script type="text/javascript" language="javascript">';
		echo '/* <![CDATA[ */';
		echo 'child_location = new Array();';
		foreach ($arr_location as $key=>$value)
		{
			echo 'child_location['.$value->id.']=new Array();';
		}
		foreach ($arr_location as $key=>$value)
			if ($value->parent_id!=0)
			{
				echo 'temp_len = child_location['.$value->parent_id.'].length;';
				echo 'child_location['.$value->parent_id.'][temp_len]='.$value->id.';';
			}
		
		echo "var data_location = [";
		$i=0;
		foreach ($arr_location as $key=>$value){
			if($i < count($arr_location)-1)
				echo "{id: 'location_".$value->id."', value: '".$value->name."'},";
			else echo "{id: 'location_".$value->id."', value: '".$value->name."'}";
			$i++;
		}
		echo "];
		
		jQuery().ready(function() {			
			jQuery('#auto_location').autocomplete(data_location, {
				minChars: 0,
				width: 250,
				matchContains: 'word',
				autoFill: false,
				formatItem: function(row, i, max) {
					return  row.value;
				},
				formatMatch: function(row, i, max) {
					return row.id + ' ' + row.value;
				},
				formatResult: function(row) {
					return row.value;
				}

			}).result(function(event, data, formatted) {				
				jQuery('#'+data.id).attr('checked', 'checked');
				checkbox_clicked(document.getElementById(data.id), 'location', 0);
				jQuery('#'+data.id).focus();				
			});
		});";	
		
		echo '/* ]]> */';
		echo '</script>';
	}
	
}


?>
